package com.project.poetry.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.poetry.common.util.CommonUtil;
import com.project.poetry.service.entity.dto.comment.CommentDTO;
import com.project.poetry.service.entity.dto.comment.ForumCommons;
import com.project.poetry.service.entity.po.common.CommentPO;
import com.project.poetry.service.entity.po.user.UserPO;
import com.project.poetry.service.mapper.CommentMapper;
import com.project.poetry.service.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 评论/追评业务层实现类
 * @author mengxj
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentPO> implements CommentService {

    @Resource
    private CommentMapper commentMapper;

    @Override
    public void releaseComment(CommentDTO comment, UserPO user) {
        CommentPO po = new CommentPO();
        BeanUtils.copyProperties(comment, po);
        po.setUserId(user.getId());
        this.commentMapper.insert(po);
    }

    @Override
    public void deleteById(Long commentId) {
        List<CommentPO> comments = this.commentMapper.selectList(new QueryWrapper<CommentPO>().lambda().eq(CommentPO :: getPrevId, commentId));
        if(CommonUtil.isNotEmpty(comments)){
            comments.forEach(comment -> this.deleteById(comment.getId()));
        }
        this.commentMapper.deleteById(commentId);
    }

    @Override
    public List<ForumCommons> getCommonsByForum(Long forumId){
        return this.commentMapper.getCommonsByForum(forumId);
    }
}
